package com.taxshare.purchaser.service;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.constant.ResultConstant;
import com.taxshare.purchaser.entity.BlackWhiteEntity;
import com.taxshare.purchaser.mapper.BlackWhiteMapper;
import com.taxshare.purchaser.remote.ApiClientService;
import com.taxshare.purchaser.util.batchHandlerUtil.BatchHandlerUtil;
import com.taxshare.purchaser.view.dto.BlackSyncDTO;
import com.taxshare.purchaser.view.dto.BlackWhiteDTO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
 * @ClassName: BlackWhiteService
 * @Description:
 * @author: hjh
 * @date: 2021/4/20 11:33
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
public class BlackWhiteService extends ServiceImpl<BlackWhiteMapper, BlackWhiteEntity> {
    @Autowired
    ApiClientService apiClientService;

    /**
     * 税号校验
     */
    public static final String TAXNUMBER_JY = "^[A-Za-z0-9]{15,20}?$";
    /**
     * 查询名单
     * 1->黑名单 ，0->白名单
     */
    public Response List(PageRequest<BlackWhiteEntity> query) {
        QueryWrapper<BlackWhiteEntity> queryWrapper = new QueryWrapper<>();
        BlackWhiteEntity blackWhiteDto = query.getInfo();
        //判断status为空
        if (StrUtil.hasBlank(blackWhiteDto.getStatus())) {
            return Response.error(ResultConstant.RET_U0004_CODE, ResultConstant.RET_U0004_MSG);
        }
        if (!StrUtil.hasBlank(blackWhiteDto.getCompanyName())) {
            queryWrapper.likeRight("company_name", blackWhiteDto.getCompanyName());
        }
        if (!StrUtil.hasBlank(blackWhiteDto.getTaxNumber())) {
            queryWrapper.likeRight("tax_number", blackWhiteDto.getTaxNumber());
        }
        if (!StrUtil.hasBlank(blackWhiteDto.getBlackType())) {
            queryWrapper.eq("black_type", blackWhiteDto.getBlackType());
        }
        queryWrapper.eq("status", blackWhiteDto.getStatus());
        queryWrapper.orderByDesc("create_time");
        IPage<BlackWhiteEntity> result = PageHelp.siamplePage(this, queryWrapper, query.getPage(), BlackWhiteEntity.class);
        return Response.success(result);
    }

    /**
     * 根据税号查询
     * @param taxNumber 税号
     * @param status 1->黑名单 ，0->白名单
     * @return
     */
    public int selectByTaxNumber(String taxNumber, String status) {
        QueryWrapper<BlackWhiteEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tax_number", taxNumber).eq("status", status);
        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 新增名单
     * 1->黑名单 ，0->白名单
     * @param blackWhiteDTO
     * @return
     */
    public Response addBlackList(BlackWhiteDTO blackWhiteDTO) {
        if (StrUtil.hasBlank(blackWhiteDTO.getCompanyName())) {
            return Response.error(ResultConstant.RET_O0006_CODE, ResultConstant.RET_O0006_MSG);
        }
        if (StrUtil.hasBlank(blackWhiteDTO.getTaxNumber())) {
            return Response.error(ResultConstant.RET_O0007_CODE, ResultConstant.RET_O0007_MSG);
        }
        //判断status为空，1->黑名单 ，0->白名单
        if (StrUtil.hasBlank(blackWhiteDTO.getStatus())) {
            return Response.error(ResultConstant.RET_U0004_CODE, ResultConstant.RET_U0004_MSG);
        }
        QueryWrapper<BlackWhiteEntity> queryWrapperByName = new QueryWrapper<>();
        queryWrapperByName.eq("company_name", blackWhiteDTO.getCompanyName());
        //对公司名判断黑白名单表中是否存在
        if (baseMapper.selectCount(queryWrapperByName) > 0) {
            List<BlackWhiteEntity> blackWhiteEntities = baseMapper.selectList(queryWrapperByName);
            for (BlackWhiteEntity blackWhiteEntity : blackWhiteEntities) {
                //已存在于黑名单
                if ("1".equals(blackWhiteEntity.getStatus())) {
                    return Response.error(ResultConstant.RET_O0009_CODE, ResultConstant.RET_O0009_MSG);
                }
                //已存在于白名单
                if ("0".equals(blackWhiteEntity.getStatus())) {
                    return Response.error(ResultConstant.RET_O0008_CODE, ResultConstant.RET_O0008_MSG);
                }
            }
        }
        QueryWrapper<BlackWhiteEntity> queryWrapperByNumber = new QueryWrapper<>();
        queryWrapperByNumber.eq("tax_number", blackWhiteDTO.getTaxNumber());
        //对税号判断黑白名单表中是否存在
        if (baseMapper.selectCount(queryWrapperByNumber) > 0) {
            List<BlackWhiteEntity> list = baseMapper.selectList(queryWrapperByNumber);
            for (BlackWhiteEntity blackWhiteEntity : list) {
                if ("1".equals(blackWhiteDTO.getStatus())) {
                    return Response.error(ResultConstant.RET_O0010_CODE, ResultConstant.RET_O0010_MSG);
                }
                if ("0".equals(blackWhiteDTO.getStatus())) {
                    return Response.error(ResultConstant.RET_O0011_CODE, ResultConstant.RET_O0011_MSG);
                }
            }
        }
        BlackWhiteEntity entity = DozerBeanUtil.map(blackWhiteDTO, BlackWhiteEntity.class);
        entity.setUuid(UUIDUitl.UUID32(false));
        //1->手工录入，2->税务局录入
        entity.setBlackType("1");
        entity.setCreateUserid(UserInfoUtil.getUserID());
        baseMapper.insert(entity);
        return Response.success();
    }

    /**
     * 删除名单
     * 1->黑名单 ，0->白名单
     * @param blackWhiteDTO
     * @return
     */
    public Response deleteList(BlackWhiteDTO blackWhiteDTO) {
        if (StrUtil.hasBlank(blackWhiteDTO.getUuid())) {
            return Response.error(ResultConstant.RET_U0004_CODE, ResultConstant.RET_U0004_MSG);
        }
        //判断status为空
        if (StrUtil.hasBlank(blackWhiteDTO.getStatus())) {
            return Response.error(ResultConstant.RET_U0004_CODE, ResultConstant.RET_U0004_MSG);
        }
        QueryWrapper<BlackWhiteEntity> Wrapper = new QueryWrapper();
        Wrapper.eq("uuid", blackWhiteDTO.getUuid()).eq("status", blackWhiteDTO.getStatus());
        baseMapper.delete(Wrapper);
        return Response.success();
    }

    /**
     * 编辑名单
     * 1->黑名单 ，0->白名单
     * @param blackWhiteDTO
     * @return
     */
    public Response editList(BlackWhiteDTO blackWhiteDTO) {
        if (StrUtil.hasBlank(blackWhiteDTO.getCompanyName())) {
            return Response.error(ResultConstant.RET_O0006_CODE, ResultConstant.RET_O0006_MSG);
        }
        if (StrUtil.hasBlank(blackWhiteDTO.getTaxNumber())) {
            return Response.error(ResultConstant.RET_O0007_CODE, ResultConstant.RET_O0007_MSG);
        }
        //uuid
        if (StrUtil.hasBlank(blackWhiteDTO.getUuid())) {
            return Response.error(ResultConstant.RET_U0004_CODE, ResultConstant.RET_U0004_MSG);
        }
        //判断status为空
        if (StrUtil.hasBlank(blackWhiteDTO.getStatus())) {
            return Response.error(ResultConstant.RET_U0004_CODE, ResultConstant.RET_U0004_MSG);
        }
        QueryWrapper<BlackWhiteEntity> queryWrapperByName = new QueryWrapper<>();
        queryWrapperByName.eq("company_name", blackWhiteDTO.getCompanyName())
                          .ne("uuid", blackWhiteDTO.getUuid());
        //对公司名判断黑白名单表中是否存在
        if (baseMapper.selectCount(queryWrapperByName) > 0) {
            List<BlackWhiteEntity> blackWhiteEntities = baseMapper.selectList(queryWrapperByName);
            for (BlackWhiteEntity blackWhiteEntity : blackWhiteEntities) {
                if ("1".equals(blackWhiteEntity.getStatus())) {
                    return Response.error(ResultConstant.RET_O0009_CODE, ResultConstant.RET_O0009_MSG);
                }
                if ("0".equals(blackWhiteEntity.getStatus())) {
                    return Response.error(ResultConstant.RET_O0008_CODE, ResultConstant.RET_O0008_MSG);
                }
            }
        }
        QueryWrapper<BlackWhiteEntity> queryWrapperByNumber = new QueryWrapper<>();
        queryWrapperByNumber.eq("tax_number", blackWhiteDTO.getTaxNumber())
                            .ne("uuid", blackWhiteDTO.getUuid());
        //对税号判断黑白名单表中是否存在
        if (baseMapper.selectCount(queryWrapperByNumber) > 0) {
            List<BlackWhiteEntity> blackWhiteEntities = baseMapper.selectList(queryWrapperByNumber);
            for (BlackWhiteEntity blackWhiteEntity : blackWhiteEntities) {
                if ("1".equals(blackWhiteEntity.getStatus())) {
                    return Response.error(ResultConstant.RET_O0010_CODE, ResultConstant.RET_O0010_MSG);
                }
                if ("0".equals(blackWhiteEntity.getStatus())) {
                    return Response.error(ResultConstant.RET_O0011_CODE, ResultConstant.RET_O0011_MSG);
                }
            }
        }
        BlackWhiteEntity entity = DozerBeanUtil.map(blackWhiteDTO, BlackWhiteEntity.class);
        if (!StrUtil.hasBlank(blackWhiteDTO.getIllegalFacts())) {
            entity.setIllegalFacts(blackWhiteDTO.getIllegalFacts());
        }
        if (!StrUtil.hasBlank(blackWhiteDTO.getNatureCase())) {
            entity.setNatureCase(blackWhiteDTO.getNatureCase());
        }
        this.updateById(entity);
        return Response.success();
    }

    /**
     * 根据省份进行黑名单同步
     *
     * @param blackSyncDTO
     * @return
     */
    public Response syncBlackInfo(BlackSyncDTO blackSyncDTO) {
        if (StrUtil.hasBlank(blackSyncDTO.getProvince())) {
            return Response.error(ResultConstant.RET_P0006_CODE, ResultConstant.RET_P0006_MSG);
        }
        Response response = apiClientService.syncBlack(blackSyncDTO);
        //内部成功标志
        if (response != null && CodeConstant.T0000.equals(response.getCode())) {
            LinkedHashMap data = (LinkedHashMap) response.getData();
            String jsonString = JSONObject.toJSONString(data);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            //第三方接口成功返回标志
            if ("T000".equals(jsonObject.get("code"))) {
                List<Map> blackList = null;
                try {
                    blackList = JSON.parseArray(jsonObject.getString("data"), Map.class);
                } catch (Exception e) {
                    log.error(">>>>>黑名单响应信息解析异常>>>>" + JSON.toJSONString(response), e);
                }
                List<BlackWhiteEntity> blackEntities = new ArrayList<>();
                if (CollUtil.isNotEmpty(blackList)) {
                    //插入黑名单表
                    for (int i = 0; i < blackList.size(); i++) {
                        BlackWhiteEntity blackEntity = new BlackWhiteEntity();
                        blackEntity.setUuid(UUIDUitl.UUID32(false));
                        blackEntity.setTaxNumber(String.valueOf(blackList.get(i).get("nsrsbh")));
                        blackEntity.setCompanyName(String.valueOf(blackList.get(i).get("qymc")));
                        blackEntity.setBlackType("2");
                        blackEntity.setNatureCase(String.valueOf(blackList.get(i).get("caseNature")));
                        blackEntity.setIllegalFacts(String.valueOf(blackList.get(i).get("caseDetail")));
                        blackEntity.setStatus("1");
                        blackEntity.setProvince(blackSyncDTO.getProvince());
                        blackEntities.add(blackEntity);
                    }
                }
                //分批插入
                if(blackEntities.size() > 0){
                    new BatchHandlerUtil<BlackWhiteEntity>().batchResolve(blackEntities, 200, (item) -> {
                        this.saveOrUpdateBatch(item);
                    });
                }
            }
        }
        return Response.success();
    }
}

//    /**
//     * 导出黑名单
//     */
//    public Response exportBlackExcel() {
//
//        QueryWrapper<BlackWhiteEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("status", "1");
//        List<BlackWhiteEntity> blackEntities = baseMapper.selectList(queryWrapper);
//        try {
//            OutputStream out = new FileOutputStream("C:/");
//            if (blackEntities != null) {
//                for (BlackWhiteEntity blackEntity : blackEntities) {
//                    ExcelHelp.writerExcel(out, , blackEntities);
//                }
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//    }

//    /**
//     * 导入黑名单
//     * @param excelFile
//     * @return
//     */
//    public Response uploadBlackExcel(MultipartFile excelFile) throws IOException {
//        //读取Excel
//        List<BlackWhiteEntity> excelContentList = ExcelHelp.readExcel(excelFile.getInputStream(), new BlackWhiteVo(),
//                BlackWhiteEntity.class);
//
//        for(int i=0; i<excelContentList.size(); i++){
//            BlackWhiteEntity model = excelContentList.get(i);
//            if(!StrUtil.hasBlank(model.getCompanyName())){
//                //企业税号
//                if(StringUtils.isBlank(model.getTaxNumber())){
//                    return Response.warnf(ResultConstant.RET_O0012_CODE,
//                            MessageFormat.format(ResultConstant.RET_O0012_MSG,String.valueOf(i+1),"企业税号"));
//                }
//                //税号规则校验
//                if (model.getTaxNumber().matches(TAXNUMBER_JY)){
//                    return Response.warnf(ResultConstant.RET_O0013_CODE,
//                            MessageFormat.format(ResultConstant.RET_O0013_MSG,String.valueOf(i+1),"企业税号"));
//                }
//
//                //案件性质
//                if (StringUtils.isBlank(model.getNatureCase())) {
//                    return Response.warnf(ResultConstant.RET_O0012_CODE,
//                            MessageFormat.format(ResultConstant.RET_O0012_MSG, String.valueOf(i + 1), "案件性质"));
//                }
//
//                //违法事实
//                if (StringUtils.isBlank(model.getIllegalFacts())) {
//                    return Response.warnf(ResultConstant.RET_O0012_CODE,
//                            MessageFormat.format(ResultConstant.RET_O0012_MSG, String.valueOf(i + 1), "违法事实"));
//                }
//            }
//        }
//        excelContentList.forEach(blackWhiteEntity -> {
//            if(StringUtils.isNotBlank(blackWhiteEntity.getCompanyName())){
//                /** 查询该数据是否被录入 */
//                QueryWrapper<BlackWhiteEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("company_name",blackWhiteEntity.getCompanyName()).eq("tax_number",blackWhiteEntity.getTaxNumber());
//                if("0".equals(baseMapper.selectCount(queryWrapper))){
//                    blackWhiteEntity.setUuid(UUIDUitl.UUID32(false));
//                    blackWhiteEntity.setStatus("1");
//                    baseMapper.insert(blackWhiteEntity);
//                };
//            }
//        });
//        return Response.success();
//    }
//
//    /**
//     *导入白名单
//     * @param excelFile
//     * @return
//     */
//    public Response uploadWhiteExcel(MultipartFile excelFile) throws IOException {
//        //读取Excel
//        List<BlackWhiteEntity> excelContentList = ExcelHelp.readExcel(excelFile.getInputStream(), new BlackWhiteVo(),
//                BlackWhiteEntity.class);
//
//        for(int i=0; i<excelContentList.size(); i++) {
//            BlackWhiteEntity model = excelContentList.get(i);
//            if (!StrUtil.hasBlank(model.getCompanyName())) {
//                //企业税号
//                if (StringUtils.isBlank(model.getTaxNumber())) {
//                    return Response.warnf(ResultConstant.RET_O0012_CODE,
//                            MessageFormat.format(ResultConstant.RET_O0012_MSG, String.valueOf(i + 1), "企业税号"));
//                }
//                //税号规则校验
//                if (model.getTaxNumber().matches(TAXNUMBER_JY)) {
//                    return Response.warnf(ResultConstant.RET_O0013_CODE,
//                            MessageFormat.format(ResultConstant.RET_O0013_MSG, String.valueOf(i + 1), "企业税号"));
//                }
//            }
//        }
//        excelContentList.forEach(blackWhiteEntity -> {
//            if(StringUtils.isNotBlank(blackWhiteEntity.getCompanyName())){
//                /** 查看数据是否已被录入*/
//                QueryWrapper<BlackWhiteEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("company_name",blackWhiteEntity.getCompanyName()).and(i-> i.eq("tax_number",blackWhiteEntity.getTaxNumber()));
//                if("0".equals(baseMapper.selectCount(queryWrapper))){
//                    blackWhiteEntity.setUuid(UUIDUitl.UUID32(false));
//                    blackWhiteEntity.setStatus("0");
//                    baseMapper.insert(blackWhiteEntity);
//                };
//            }
//
//        });
//        return Response.success();
//    }



